using System;
using System.Linq;
using System.Security.Principal;
using GiveGraphMappers;
using GiveGraphModel;
using Microsoft.IdentityModel.Claims;

namespace WebApp.Util
{
    public static class Utils
    {
        public static int GetUserId(this IClaimsIdentity identity)
        {
            string email = (from p in identity.Claims
                               where p.ClaimType == ClaimTypes.Email
                               select p.Value).SingleOrDefault();

            UserMapper mapper = new UserMapper();
            Member member;
            if ((member = mapper.GetByEmail(email)) != null)
                return member.MemberId;
            if((member = new OrganizationMapper().GetByEmail(email)) != null)
                return member.MemberId;

            //throw new InvalidProgramException();
            return -1;
        }

        public static bool IsRegistered(this IClaimsIdentity identity)
        {
            string email = (from p in identity.Claims
                            where p.ClaimType == ClaimTypes.Email
                            select p.Value).SingleOrDefault();

            UserMapper userMapper = new UserMapper();

            OrganizationMapper orgMapper = new OrganizationMapper();

            return userMapper.UserExists(email) || orgMapper.OrganizationExists(email);
        }

        public static bool IsUserInRole(this IPrincipal principal, string role)
        {
            UserMapper mapper = new UserMapper();
            OrganizationMapper mapperOrg = new OrganizationMapper();

            GiveGraphModel.User user = null;
            Organization organization = null;
            bool ret = false;

            try
            {
                IClaimsIdentity identity = ((IClaimsIdentity) principal.Identity);
                user = mapper.Get(identity.GetUserId());
                organization = mapperOrg.Get(identity.GetUserId());
            }
            catch(InvalidOperationException){}
            finally
            {
                if (user == null && role.Equals("Organization"))
                    ret = true;
                if (user != null && organization == null && role.Equals("User"))
                    ret = true;
            }
            return ret ? ret : principal.IsInRole(role);
        }

        public static long GetFacebookUserId(string acessToken)
        {
            var id = acessToken.Split('-')[1].Split('|');
            var idUser = long.Parse(id[0]);
            return idUser;
        }

    }
}